package com.yylending.las.lending.quota.idcard;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.*;
import android.view.animation.LinearInterpolator;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.CLog;
import com.yyfax.common.roundedimageview.RoundedImageView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.*;
import com.yylending.las.authority.login.LoginActivity;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.VibratorUtil;
import com.yylending.las.common.widgets.BaseDialog;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.quota.ApplyQuotaActivity;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoModel;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoPresenter;
import com.yylending.las.lending.quota.entity.CustomerBean;
import exocr.engine.EngineManager;
import exocr.engine.ViewEvent;
import exocr.exocrengine.EXIDCardResult;
import exocr.idcard.IDCardManager;
import ocr.idcard.ViewfinderView;
import org.apaches.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;

/**
 * Created by laixj on 2016/11/9.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class IdCardScanFragment extends BaseFragment implements IdCardPresenter.View, CustomerInfoPresenter.View, View.OnClickListener, ViewEvent {
	private final static String TAG = "IdCardScanFragment";

	private final static int LOADER_ID_ID_CARD = 1;
	private final static int LOADER_ID_CUSTOMER_INFO = 2;

	// 需要存储权限和照相机权限同时授权.
	private static final int PERMISSION_REQUEST_CODE_DEFAULT = 1;
	private static final int PERMISSION_REQUEST_CODE_SCAN_FRONT_ID_CARD = 2;
	private static final int PERMISSION_REQUEST_CODE_SCAN_BACK_ID_CARD = 3;

	@BindView(R.id.my_limit_idcard_front)
	RoundedImageView mFrontIv;
	@BindView(R.id.my_limit_idcard_front_mask)
	RoundedImageView mIdcardFrontMask;
	@BindView(R.id.idcard_front_camera_iv)
	ImageView mFrontCameraIv;
	@BindView(R.id.idcard_front_hint)
	TextView mIdcardFrontHint;
	@BindView(R.id.my_limit_idcard_back)
	RoundedImageView mBackIv;
	@BindView(R.id.my_limit_idcard_back_mask)
	RoundedImageView mIdcardBackMask;
	@BindView(R.id.idcard_back_camera_iv)
	ImageView mBackCameraIv;
	@BindView(R.id.idcard_back_hint)
	TextView mIdcardBackHint;
	@BindView(R.id.id_card_front_rl)
	RelativeLayout mIdCardFrontRl;
	@BindView(R.id.id_card_back_rl)
	RelativeLayout mIdCardBackRl;
	Unbinder unbinder;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;
	@BindView(R.id.id_card_info_name_str)
	TextView mNameStr;
	@BindView(R.id.id_card_info_name_et)
	EditText mNameEt;
	@BindView(R.id.id_card_name_delete_iv)
	ImageView mNameDeleteIv;
	@BindView(R.id.id_card_info_number_str)
	TextView mNumberStr;
	@BindView(R.id.id_card_info_number_et)
	TextView mNumberEt;
	@BindView(R.id.id_card_info_office_str)
	TextView mOfficeStr;
	@BindView(R.id.id_card_info_office)
	EditText mOfficeEt;
	@BindView(R.id.id_card_info_period_str)
	TextView mPeriodStr;
	@BindView(R.id.id_card_info_period_start)
	TextView mPeriodStartTv;
	@BindView(R.id.id_card_info_submit)
	Button mSubmit;
	@BindView(R.id.id_card_info_ll)
	LinearLayout mIdCardInfoLl;
	@BindView(R.id.id_card_info_office_delete_iv)
	ImageView mOfficeDeleteIv;

	private View mCustomerView;
	private TextView mBackTv;
	private TextView mBottomTv;
	private ImageView mHintImg;
	private ViewfinderView mViewfinderView;

	private IdCardPresenter mIdCardPresenter;
	private CustomerInfoPresenter mCustomerInfoPresenter;

	//是否正在操作
	private boolean mOperating = false;
	//身份证扫描结果
	private EXIDCardResult mEXIDCardResult;
	private boolean mHeadUploaded;
	private boolean mFrontUploaded;
	private boolean mBackUploaded;
	//是否已经显示过动画
	private boolean mAnimBeenShown;
	private IdCardModel.IdCard mIdCard = new IdCardModel.IdCard();
	private boolean mInitCompleted;
	private Bitmap mFrontImage;
	private Bitmap mBackImage;
	private float mDensity = 2.0f;
	private float mScale = 346 / 546.0f;
	private IdCardConfirmDialog mConfirmDialog;

	private int mOriginalGapDp = 43;
	private int mFrontMarginTopDp = 38;
	private int mBackMarginTopDp = 26;

	private int mIdCardImgWidth, mIdCardImgHeight, mFrontMarginTop;

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {
			switch (requestCode) {
				// 需要存储和照相机权限同时授权.
				case PERMISSION_REQUEST_CODE_SCAN_FRONT_ID_CARD:
					if (granted) {
						scanFront(false);
					} else {
						mOperating = false;
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
					break;
				case PERMISSION_REQUEST_CODE_SCAN_BACK_ID_CARD:
					if (granted) {
						scanBack(false);
					} else {
						mOperating = false;
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}
		}
	};

	public static BaseFragment newInstance(int sectionNumber) {
		BaseFragment fragment = new IdCardScanFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		mDensity = getResources().getDisplayMetrics().density;
		mIdCardImgWidth = getResources().getDisplayMetrics().widthPixels - DensityUtil.dip2px(getContext(), mOriginalGapDp * 2);
		mIdCardImgHeight = (int) (mIdCardImgWidth * mScale);
		mFrontMarginTop = DensityUtil.dip2px(getContext(), mFrontMarginTopDp);

		CLog.i(TAG, "mIdCardImgWidth->" + mIdCardImgWidth);
		CLog.i(TAG, "mIdCardImgHeight->" + mIdCardImgHeight);
	}

	@Override
	public void onResume() {
		super.onResume();
		CLog.i(TAG, "IdCardScanFragment onResume()->");
		if (!mInitCompleted) {
			mInitCompleted = true;
			//judgeStep();
		}
		mOperating = false;
		if (isComplete() && !mAnimBeenShown) {
			startAnimation();
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		CLog.i(TAG, "onStart()->");
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	public void onStop() {
		CLog.i(TAG, "IdCardScanFragment onStop()->");
		super.onStop();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			CLog.i(TAG, "onHiddenChanged hidden->" + hidden);
			judgeStep();
		}
	}

	private void judgeStep() {
		CLog.i(TAG, "当前显示页->" + ((ApplyQuotaActivity) getActivity()).getmCurrentPage());
		CLog.i(TAG, "YJKD.isRealName()->" + YJKD.isRealName());
		if (((ApplyQuotaActivity) getActivity()).getmCurrentPage() == ApplyQuotaActivity.PAGE_ID_CARD_SCAN) {
			if (YJKD.isRealName()) {
				((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_ID_CARD_CONFIRM, mIdCard);
			} else {
				RelativeLayout.LayoutParams idCardFrontLayoutParams = (RelativeLayout.LayoutParams) mIdCardFrontRl.getLayoutParams();
				idCardFrontLayoutParams.width = mIdCardImgWidth;
				idCardFrontLayoutParams.height = mIdCardImgHeight;
				idCardFrontLayoutParams.setMargins(DensityUtil.dip2px(getContext(), mOriginalGapDp), DensityUtil.dip2px(getContext(), mFrontMarginTopDp), DensityUtil.dip2px(getContext(), mOriginalGapDp), 0);
				mIdCardFrontRl.setLayoutParams(idCardFrontLayoutParams);
				RelativeLayout.LayoutParams idCardBackLayoutParams = (RelativeLayout.LayoutParams) mIdCardBackRl.getLayoutParams();
				idCardBackLayoutParams.width = mIdCardImgWidth;
				idCardBackLayoutParams.height = mIdCardImgHeight;
				idCardBackLayoutParams.setMargins(DensityUtil.dip2px(getContext(), mOriginalGapDp), DensityUtil.dip2px(getContext(), mBackMarginTopDp), DensityUtil.dip2px(getContext(), mOriginalGapDp), 0);
				mIdCardBackRl.setLayoutParams(idCardBackLayoutParams);

				mIdCardFrontRl.setVisibility(View.VISIBLE);
				mIdcardFrontHint.setVisibility(View.VISIBLE);
				mIdCardBackRl.setVisibility(View.VISIBLE);
				mIdcardBackHint.setVisibility(View.VISIBLE);
				if (PermissionsGrantedHelper.isSdkUnderM()) {
					if (PermissionsGrantedHelper.checkCameraPermission()) {
						// TODO: 2016/12/6
						CLog.i(TAG, "相机权限已打开");
					} else {
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
				} else {
					PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, mGrantedListener, PERMISSION_REQUEST_CODE_DEFAULT, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
				}
			}
		}
	}

	private void checkStatus() {
		if (YJKD.login()) {
			EngineManager.getInstance().initEngine(getActivity());
			IDCardManager.getInstance().setView(mCustomerView);
		} else {
			LoginActivity.start((RxAppCompatActivity) getActivity());
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_ID_CARD:
				return new PresenterLoader<>(getActivity(), new IdCardPresenter.Generator());
			case LOADER_ID_CUSTOMER_INFO:
				return new PresenterLoader<>(getActivity(), new CustomerInfoPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_ID_CARD:
				CLog.i(TAG, "onLoadFinished() BaseInfoPresenter");
				mIdCardPresenter = (IdCardPresenter) data;
				mIdCardPresenter.attach(this);
				break;
			case LOADER_ID_CUSTOMER_INFO:
				CLog.i(TAG, "onLoadFinished() CustomerInfoPresenter");
				mCustomerInfoPresenter = (CustomerInfoPresenter) data;
				mCustomerInfoPresenter.attach(this);
				mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_IDENTITY);
				break;
		}
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		checkStatus();
		//EventAgent.register(this);
	}

	@Override
	public void onDestroyView() {
		//EventAgent.unregister(this);
		//IDCardManager.getInstance().stopRecognize();
		dismissConfirmDialog();
		EngineManager.getInstance().finishEngine();
		super.onDestroyView();
		unbinder.unbind();
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_ID_CARD, null, this);
		getLoaderManager().initLoader(LOADER_ID_CUSTOMER_INFO, null, this);
	}

	@Override
	public void onDetach() {
		getLoaderManager().destroyLoader(LOADER_ID_ID_CARD);
		getLoaderManager().destroyLoader(LOADER_ID_CUSTOMER_INFO);
		super.onDetach();
		CLog.i(TAG, "onDetach()");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_my_limit_idcard_scan, null);
		unbinder = ButterKnife.bind(this, v);
		mFrontCameraIv.setOnClickListener(this);
		mBackCameraIv.setOnClickListener(this);
		mNoNetworkLayout.setOnClickListener(this);
		mNameDeleteIv.setOnClickListener(this);
		mOfficeDeleteIv.setOnClickListener(this);
		mSubmit.setOnClickListener(this);
		mNameEt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().trim().length() != 0) {
					mNameDeleteIv.setVisibility(View.VISIBLE);
				} else {
					mNameDeleteIv.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		mOfficeEt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().trim().length() != 0) {
					mOfficeDeleteIv.setVisibility(View.VISIBLE);
				} else {
					mOfficeDeleteIv.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		mCustomerView = inflater.inflate(R.layout.activity_capture, null);
		mBackTv = (TextView) mCustomerView.findViewById(R.id.idcard_scan_back_tv);
		mBottomTv = (TextView) mCustomerView.findViewById(R.id.idcard_scan_bottom);
		mHintImg = (ImageView) mCustomerView.findViewById(R.id.idcard_scan_hint_iv);
		mViewfinderView = (ViewfinderView) mCustomerView.findViewById(R.id.idcard_scan_finderview);
		mBackTv.setOnClickListener(this);
		return v;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.idcard_front_camera_iv:
				if (isComplete()) {
					//如果正反面已经全部扫描完成，则统计重拍事件
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_TAKE_PHOTO_AGAIN);
				} else {
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_ID_CARD_FRONT_TAKE_PHOTOS);
				}
				if (!mOperating) {
					if (PermissionsGrantedHelper.isSdkUnderM()) {
						// TODO: 2017/6/15 这个判断只在魅族手机上有效?
						if (PermissionsGrantedHelper.checkCameraPermission()) {
							scanFront(false);
						} else {
							mOperating = false;
							showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
						}
					} else {
						PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, mGrantedListener, PERMISSION_REQUEST_CODE_SCAN_FRONT_ID_CARD, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
					}
				}
				break;
			case R.id.idcard_back_camera_iv:
				if (isComplete()) {
					//如果正反面已经全部扫描完成，则统计重拍事件
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_TAKE_PHOTO_AGAIN);
				} else {
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_ID_CARD_OPPOSITE_TAKE_PHOTOS);
				}
				if (!mOperating) {
					if (PermissionsGrantedHelper.isSdkUnderM()) {
						// TODO: 2017/6/15 这个判断只在魅族手机上有效?
						if (PermissionsGrantedHelper.checkCameraPermission()) {
							scanBack(false);
						} else {
							mOperating = false;
							showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
						}
					} else {
						PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, mGrantedListener, PERMISSION_REQUEST_CODE_SCAN_BACK_ID_CARD, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
					}
				}
				break;
			case R.id.idcard_scan_back_tv:
				// 扫描返回键
				IDCardManager.getInstance().stopRecognize();
				break;
			case R.id.no_network_layout:
				mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_IDENTITY);
				break;
			case R.id.id_card_name_delete_iv:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CLEAR_ID_CARD_NAME);
				mNameEt.getText().clear();
				break;
			case R.id.id_card_info_office_delete_iv:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CLEAR_ID_CARD_OFFICE);
				mOfficeEt.getText().clear();
				break;
			case R.id.id_card_info_submit:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CLICK_SAVE_ID_CARD_BUTTON);
				if (null != mIdCard && validate())
					showConfirmDialog();
				break;
		}
	}

	private void showConfirmDialog() {
		if (null == mConfirmDialog) {
			mConfirmDialog = new IdCardConfirmDialog(getActivity(), "", "", getString(R.string.confirm_ok), getString(R.string.return_modify), new BaseDialog.ButtonClickListener() {
				@Override
				public void onCancel(BaseDialog dialog) {
					dialog.dismiss();
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_SAVE_ID_CARD_EDIT);
					mNameEt.setFocusable(true);
					mNameEt.requestFocus();
					mNameEt.setSelection(mNameEt.getText().length());
					YJKD.showInputWindow();
				}

				@Override
				public void onConfirm(BaseDialog dialog) {
					dialog.dismiss();
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_SAVE_ID_CARD_CONFIRM);
					submitIdCardInfo();
				}
			}, true, R.layout.dialog_confirm_id_card_info, mIdCard.iname, mIdCard.inumber);
			mConfirmDialog.setBtnHeight(DensityUtil.dip2px(getContext(), 44));
			mConfirmDialog.setLeftBtnTextSize(14);
			mConfirmDialog.setRightBtnTextSize(14);
			mConfirmDialog.setDialogWidth(DensityUtil.dip2px(getContext(), 288));
		} else {
			mConfirmDialog.setIdCardName(mIdCard.iname);
			mConfirmDialog.setIdCardNumber(mIdCard.inumber);
		}
		mConfirmDialog.show();
	}

	private void dismissConfirmDialog() {
		if (mConfirmDialog != null && mConfirmDialog.isShowing()) {
			mConfirmDialog.dismiss();
			mConfirmDialog = null;
		}
	}

	private class IdCardConfirmDialog extends BaseDialog {

		private String mIdCardName;
		private String mIdCardNumber;

		public IdCardConfirmDialog(Context ctx, String title, String content, String confirmString, String cancelString,
				ButtonClickListener listener, boolean cancelAble, int contentLayoutId, String idCardName, String idCardNumber) {
			super(ctx, title, content, confirmString, cancelString, listener, cancelAble, contentLayoutId);
			mIdCardName = idCardName;
			mIdCardNumber = idCardNumber;
		}

		@Override
		protected void initSpecialContent() {
			((TextView) findViewById(R.id.id_card_info_name)).setText(mIdCardName);
			((TextView) findViewById(R.id.id_card_info_number)).setText(mIdCardNumber);
		}

		public void setIdCardName(String idCardName) {
			mIdCardName = idCardName;
			((TextView) findViewById(R.id.id_card_info_name)).setText(mIdCardName);
		}

		public void setIdCardNumber(String idCardNumber) {
			mIdCardNumber = idCardNumber;
			((TextView) findViewById(R.id.id_card_info_number)).setText(mIdCardNumber);
		}

		@Override
		public void show() {
			Window dialogWindow = getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.TOP);
			//lp.x = 100; // 新位置X坐标
			//按比例设置距离顶部的高度
			int y = (int)(350 / 1280.0f * getResources().getDisplayMetrics().heightPixels);
			lp.y = y;//新位置Y坐标
			//lp.width = DensityUtil.dip2px(getContext(), 288); // 宽度 设置无效
			//lp.height = 800; // 高度 设置无效
			//lp.alpha = 0.7f; // 透明度

			// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
			// dialog.onWindowAttributesChanged(lp);
			dialogWindow.setAttributes(lp);
			super.show();
		}
	}

	private boolean validate() {
		if (null == mIdCard) {
			showToast(R.string.scan_id_card_fail);
			return false;
		}
		mIdCard.inumber = mNumberEt.getText().toString().toUpperCase();
		mIdCard.iname = mNameEt.getText().toString().trim();
		mIdCard.ioffice = mOfficeEt.getText().toString().trim();
		if (TextUtils.isEmpty(mIdCard.iname)) {
			showToast(R.string.id_card_name_number_error);
			return false;
		}
		if (TextUtils.isEmpty(mIdCard.inumber)) {
			showToast(R.string.id_card_name_number_error);
			return false;
		}
		if (mIdCard.inumber.length() < 18) {
			showToast(R.string.id_card_name_number_error);
			return false;
		}
		if (TextUtils.isEmpty(mIdCard.ioffice)) {
			showToast(R.string.id_card_office_error);
			return false;
		}
		if (TextUtils.isEmpty(mIdCard.istart) || TextUtils.isEmpty(mIdCard.iend)) {
			showToast(R.string.scan_id_card_fail);
			return false;
		}
		return true;
	}

	private void submitIdCardInfo() {
		if (mIdCard.iend.contains("长期")) {
			mIdCard.iend = "20990101";
		}
		CLog.i(TAG, "提交身份证信息--" + mIdCard.toString());
		YJKD.hideInputWindow(getActivity());
		showLoading(true);
		mIdCardPresenter.saveIdCardInfo(mIdCard);
	}

	private void scanFront(boolean isContinue) {
		mOperating = true;
		//忽略手势密码
		Global.setThirdPartyPageOpenedFlag(true);
		mBottomTv.setText(R.string.put_foreground_center);
		mHintImg.setImageResource(R.drawable.id_forground_img);
		mViewfinderView.setFront(true);
		if (isContinue) {
			IDCardManager.getInstance().continueRecognizeWithSide(true);
		} else {
			IDCardManager.getInstance().recognizeWithSide(this, getActivity(), true);
		}
	}

	private void scanBack(boolean isContinue) {
		mOperating = true;
		//忽略手势密码
		Global.setThirdPartyPageOpenedFlag(true);
		mBottomTv.setText(R.string.put_background_center);
		mHintImg.setImageResource(R.drawable.id_background_img);
		mViewfinderView.setFront(false);
		if (isContinue) {
			IDCardManager.getInstance().continueRecognizeWithSide(false);
		} else {
			IDCardManager.getInstance().recognizeWithSide(this, getActivity(), false);
		}
	}

	private void showNeedPermission(String tips){
		showTwoBtnDialog(tips, getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	/**
	 * 把Bitmap转Byte
	 */
	public static byte[] bitmap2Bytes(Bitmap bm, int quality) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
		return baos.toByteArray();
	}

	@Override
	public void onCardDetected(Parcelable parcelable) {
		VibratorUtil.vibrate(getActivity(), 100);
		mEXIDCardResult = (EXIDCardResult) parcelable;
		if (mEXIDCardResult != null) {
			CLog.i(TAG, "IDCardFragment onActivityResult capture not null");
			int type = mEXIDCardResult.type;
			CLog.i(TAG, "IDCardFragment onActivityResult capture type=" + type);
			if (type == 1) {//正面
				try {
					mIdCard.inumber = mEXIDCardResult.cardnum;
					mIdCard.iname = mEXIDCardResult.name;
					mFrontImage = mEXIDCardResult.stdCardIm;
					CLog.i(TAG, "IDCardFragment onActivityResult 正面照-->" + mFrontImage.getByteCount());
					mFrontIv.setImageBitmap(mFrontImage);
					mIdcardFrontMask.setVisibility(View.VISIBLE);
					//mIdcardFrontHint.setVisibility(View.VISIBLE);
					mIdCard.iaddress = mEXIDCardResult.address;
					mIdCard.isex = mEXIDCardResult.sex;
					mIdCard.iregion = mEXIDCardResult.nation;
					mIdCard.iavatar = Base64.encodeBase64String(bitmap2Bytes(mEXIDCardResult.GetFaceBitmap(), 100));
					mIdCard.ipicFront = Base64.encodeBase64String(bitmap2Bytes(mEXIDCardResult.stdCardIm, 70));
					CLog.i(TAG, "身份证正面-->" + mIdCard.ipicFront.length());
					CLog.i(TAG, "身份证头像-->" + mIdCard.iavatar.length());

					mNameEt.setText(mIdCard.iname);
					mNumberEt.setText(mIdCard.inumber);
					mNameEt.setSelection(mNameEt.getText().length());

					mHeadUploaded = true;
					mFrontUploaded = true;
					if (isComplete()) {
						IDCardManager.getInstance().stopRecognize();
						//if(!mAnimBeenShown) startAnimation();
					} else {
						if (!mBackUploaded) {
							//IDCardManager.getInstance().stopRecognize();
							CLog.i(TAG, "自动切换到背面扫描");
							// TODO: 2017/11/27  翻转动画
							scanBack(true);
						}
					}
				} catch (Exception e) {
					// TODO: 2016/12/9
				}
			} else {//反面
				try {
					mIdCard.ioffice = mEXIDCardResult.office;
					if (mEXIDCardResult.validdate.contains("-")) {
						mIdCard.istart = mEXIDCardResult.validdate.split("-")[0];
						mIdCard.iend = mEXIDCardResult.validdate.split("-")[1];
					} else {
						mIdCard.istart = "";
						mIdCard.iend = "";
					}
					mBackImage = mEXIDCardResult.stdCardIm;
					CLog.i(TAG, "IDCardFragment onActivityResult 反面照-->" + mBackImage.getByteCount());
					mBackIv.setImageBitmap(mBackImage);
					mIdCard.ipicBack = Base64.encodeBase64String(bitmap2Bytes(mEXIDCardResult.stdCardIm, 70));
					CLog.i(TAG, "身份证背面-->" + mIdCard.ipicBack.length());
					mIdcardBackMask.setVisibility(View.VISIBLE);
					//mIdcardBackHint.setVisibility(View.VISIBLE);
					mBackUploaded = true;

					mOfficeEt.setText(mIdCard.ioffice);
					mPeriodStartTv.setText(FormatUtils.formatIdCardValidDate(mIdCard.istart) + "-" + FormatUtils.formatIdCardValidDate(mIdCard.iend));

					if (isComplete()) {
						IDCardManager.getInstance().stopRecognize();
						//if(!mAnimBeenShown) startAnimation();
					} else {
						if (!mHeadUploaded && !mFrontUploaded) {
							//IDCardManager.getInstance().stopRecognize();
							CLog.i(TAG, "自动切换到正面扫描");
							// TODO: 2017/11/27  翻转动画
							scanFront(true);
						}
					}
				} catch (Exception e) {
					// TODO: 2016/12/9
				}
			}
		}
	}

	@Override
	public Rect getRectByOrientation(int i) {
		return null;
	}

	@Override
	public void invalideView(int i) {

	}

	@Override
	public void onTimeOut() {

	}

	@Override
	public void refreshScanViewByRecoContnueWithSide(boolean b) {

	}

	@Override
	public void onBack() {
		CLog.i(TAG, "onBack()---");
	}

	@Override
	public void onLightChanged(float v) {

	}

	@Override
	public void onPauseRecognize() {

	}

	@Override
	public void onRecoErrorWithWrongSide() {

	}

	@Override
	public void onCameraDenied() {
		CLog.i(TAG, "onCameraDenied()---");
		mOperating = false;
	}

	private boolean isComplete() {
		if (mHeadUploaded && mFrontUploaded && mBackUploaded) {
			return true;
		}
		return false;
	}

	@Override
	public void customerInfoExist(String type, CustomerBean customerBean) {
		if (Constants.CUSTOMER_TYPE_IDENTITY.equals(type)) {
			showReloadView(View.GONE);
			mIdCard = customerBean.identity;
			judgeStep();
		}
	}

	@Override
	public void customerInfoNotExist(String type, String msg) {
		if (Constants.CUSTOMER_TYPE_IDENTITY.equals(type)) {
			showReloadView(View.GONE);
			mIdCard = new IdCardModel.IdCard();
			judgeStep();
		}
	}

	@Override
	public void getCustomerInfoError(String type, String msg) {
		if (Constants.CUSTOMER_TYPE_IDENTITY.equals(type)) {
			showReloadView(View.VISIBLE);
		}
	}

	@Override
	public void saveIdCardSuccess() {
		dismissLoading();
		Global.LOGIN_REAL_NAME = mIdCard.iname;
		//((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_ID_CARD_CONFIRM, mIdCard);
		((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_FACE, null);
	}

	@Override
	public void saveIdCardFail(String msg, boolean exit) {
		dismissLoading();
		if (exit) {
			showOneBtnDialog(msg, getString(R.string.got_it), mExitDialog);
		} else {
			showOneBtnDialog(msg, getString(R.string.got_it));
		}
	}

	private CommonDialog.ButtonClickListener mExitDialog = new CommonDialog.ButtonClickListener() {
		@Override
		public void onCancel(CommonDialog dialog) {
			dialog.dismiss();
		}

		@Override
		public void onConfirm(CommonDialog dialog) {
			dialog.dismiss();
			getActivity().finish();
		}
	};

	private void showReloadView(int visible) {
		if ((visible == View.GONE && mNoNetworkLayout.getVisibility() == View.VISIBLE)
				|| (visible == View.VISIBLE && mNoNetworkLayout.getVisibility() == View.GONE)) {
			mNoNetworkLayout.setVisibility(visible);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case CustomerInfoModel.METHOD_CUSTOMER_INFO:
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showReloadView(View.VISIBLE);
					}
				});
				break;
		}
	}

	private void startAnimation() {
		mAnimBeenShown = true;
		mIdCardInfoLl.setVisibility(View.GONE);
		int animDuration = 800;
		int screenWidth = getResources().getDisplayMetrics().widthPixels;
		int hintTextHeight = mIdcardFrontHint.getHeight();
		int newGap = DensityUtil.dip2px(getContext(), 16);

		float scale = (screenWidth - 3 * newGap) * 1.0f / 2 / mIdCardImgWidth;
		float textScale = 0.8571f;

		ObjectAnimator frontXScaleAnim = ObjectAnimator.ofFloat(mIdCardFrontRl, "scaleX", 1.0f, scale);
		ObjectAnimator frontYScaleAnim = ObjectAnimator.ofFloat(mIdCardFrontRl, "scaleY", 1.0f, scale);
		ObjectAnimator frontXTransAnim = ObjectAnimator.ofFloat(mIdCardFrontRl, "translationX", 0, -screenWidth / 2 + mIdCardFrontRl.getWidth() * scale / 2 + newGap);
		ObjectAnimator frontYTransAnim = ObjectAnimator.ofFloat(mIdCardFrontRl, "translationY", 0, -mIdCardFrontRl.getHeight() * (1 - scale) / 2 - mFrontMarginTop + newGap);
		AnimatorSet frontAnimSet = new AnimatorSet();
		frontAnimSet.setDuration(animDuration);
		frontAnimSet.setInterpolator(new LinearInterpolator());
		frontAnimSet.play(frontXScaleAnim).with(frontYScaleAnim).with(frontXTransAnim).with(frontYTransAnim);

		ObjectAnimator backXScaleAnim = ObjectAnimator.ofFloat(mIdCardBackRl, "scaleX", 1.0f, scale);
		ObjectAnimator backYScaleAnim = ObjectAnimator.ofFloat(mIdCardBackRl, "scaleY", 1.0f, scale);
		ObjectAnimator backXTransAnim = ObjectAnimator.ofFloat(mIdCardBackRl, "translationX", 0, screenWidth / 2 - mIdCardFrontRl.getWidth() * scale / 2 - newGap);
		ObjectAnimator backYTransAnim = ObjectAnimator.ofFloat(mIdCardBackRl, "translationY", 0, -mIdCardFrontRl.getHeight() * (1 - scale) / 2 - mIdCardFrontRl.getHeight() - hintTextHeight
				- DensityUtil.dip2px(getContext(), 35) - mFrontMarginTop + newGap);
		AnimatorSet backAnimSet = new AnimatorSet();
		backAnimSet.setDuration(animDuration);
		backAnimSet.setInterpolator(new LinearInterpolator());
		backAnimSet.play(backXScaleAnim).with(backYScaleAnim).with(backXTransAnim).with(backYTransAnim);

		mIdcardFrontHint.setText(R.string.id_card_front);
		ObjectAnimator frontTextXScaleAnim = ObjectAnimator.ofFloat(mIdcardFrontHint, "scaleX", 1.0f, textScale);
		ObjectAnimator frontTextYScaleAnim = ObjectAnimator.ofFloat(mIdcardFrontHint, "scaleY", 1.0f, textScale);
		ObjectAnimator frontTextXTransAnim = ObjectAnimator.ofFloat(mIdcardFrontHint, "translationX", 0, -screenWidth / 2 + mIdCardFrontRl.getWidth() * scale / 2 + newGap);
		ObjectAnimator frontTextYTransAnim = ObjectAnimator.ofFloat(mIdcardFrontHint, "translationY", 0, -mIdCardFrontRl.getHeight() * (1 - scale) - mFrontMarginTop + newGap - DensityUtil.dip2px(getContext(), 2));
		AnimatorSet frontTextAnimSet = new AnimatorSet();
		frontTextAnimSet.setDuration(animDuration);
		frontTextAnimSet.setInterpolator(new LinearInterpolator());
		frontTextAnimSet.play(frontTextXScaleAnim).with(frontTextYScaleAnim).with(frontTextXTransAnim).with(frontTextYTransAnim);

		mIdcardBackHint.setText(R.string.id_card_back);
		ObjectAnimator backTextXScaleAnim = ObjectAnimator.ofFloat(mIdcardBackHint, "scaleX", 1.0f, textScale);
		ObjectAnimator backTextYScaleAnim = ObjectAnimator.ofFloat(mIdcardBackHint, "scaleY", 1.0f, textScale);
		ObjectAnimator backTextXTransAnim = ObjectAnimator.ofFloat(mIdcardBackHint, "translationX", 0, screenWidth / 2 - mIdCardFrontRl.getWidth() * scale / 2 - newGap);
		ObjectAnimator backTextYTransAnim = ObjectAnimator.ofFloat(mIdcardBackHint, "translationY", 0, -mIdCardFrontRl.getHeight() * (1 - scale) - mIdCardFrontRl.getHeight() - hintTextHeight
				- DensityUtil.dip2px(getContext(), 35) - mFrontMarginTop + newGap - DensityUtil.dip2px(getContext(), 2));
		AnimatorSet backTextAnimSet = new AnimatorSet();
		backTextAnimSet.setDuration(animDuration);
		backTextAnimSet.setInterpolator(new LinearInterpolator());
		backTextAnimSet.play(backTextXScaleAnim).with(backTextYScaleAnim).with(backTextXTransAnim).with(backTextYTransAnim);

		RelativeLayout.LayoutParams idCardInfoLayoutParams = (RelativeLayout.LayoutParams) mIdCardInfoLl.getLayoutParams();
		int marginTop = newGap + (int) (mIdCardBackRl.getHeight() * scale) + (int) (hintTextHeight * textScale)
				+ DensityUtil.dip2px(getContext(), 9);
		idCardInfoLayoutParams.setMargins(0, marginTop, 0, 0);
		mIdCardInfoLl.setLayoutParams(idCardInfoLayoutParams);

		frontAnimSet.start();
		backAnimSet.start();
		frontTextAnimSet.start();
		backTextAnimSet.start();

		final ObjectAnimator idCardInfoAlphaAnim = ObjectAnimator.ofFloat(mIdCardInfoLl, "alpha", 0f, 1f);
		idCardInfoAlphaAnim.setDuration(animDuration);
		idCardInfoAlphaAnim.setInterpolator(new LinearInterpolator());

		backTextYTransAnim.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				mIdCardInfoLl.setVisibility(View.VISIBLE);
				idCardInfoAlphaAnim.start();
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});
	}
}